package cn.tedu.oa_system.service.impl;

import cn.tedu.oa_system.mapper.UserLoginRecordMapper;
import cn.tedu.oa_system.mapper.UserMapper;
import cn.tedu.oa_system.pojo.UserLoginRecord;
import cn.tedu.oa_system.pojo.model.UserInfo;
import cn.tedu.oa_system.service.LoginService;
import com.alibaba.fastjson.JSON;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author MW
 * @Description
 * @CreateDate 2023/2/28
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;


    // Token中的密钥
    private String secretKey = "jfdsfdslkjafdslkjafds";


    @Override
    public String login(UserInfo userInfo) {
        Authentication authentication
                =new UsernamePasswordAuthenticationToken(
                userInfo.getUsername(),userInfo.getPassword());

        Authentication authenticate = authenticationManager.authenticate(authentication);

        //若执行到这,说明登录成功
        User user = (User) authenticate.getPrincipal();
        log.debug("认证成功,Spring Security返回结果中的getPrincipal():{}",user);
        log.debug("Spring Security返回结果中的getPrincipal()的类型:{}",user.getClass().getName());
        Map<String, Object> claims=new HashMap<>();
        claims.put("username",user.getUsername());
        claims.put("permissions", JSON.toJSONString(user.getAuthorities()));
        JwtBuilder builder = Jwts.builder();
        String jwt = builder
                .setHeaderParam(Header.TYPE, Header.JWT_TYPE)
                .setHeaderParam(Header.CONTENT_TYPE, "HS256")
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + 5 * 50 * 60 * 1000))
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();

        return jwt;
    }
}
